package cn.shengchao.wecom.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.wecom.configure.WxCpConfiguration;
import cn.shengchao.wecom.configure.WxCpProperties;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayInfo;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayResult;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.continew.starter.core.exception.BaseException;

import java.util.List;

/**
 * @program: examstarapi
 * @description: 客户联系请求功能
 * @author: Xiong weiqiang
 * @create: 2025-04-10 17:50
 */
@Component
public class WeComExternalContactHelper {
    private static final String CHECK_USER_FOLLOW_USER_URL ="/externalcontact/check_follow_user";
    @Autowired
    private WxCpProperties wxCpProperties;
    public Integer getAgentId(int index){
        Integer agentId = wxCpProperties.getAppConfigs().get(index).getAgentId();
        if (ObjectUtil.isNull(agentId)) {throw new BaseException("企微应用id没有配置");}
        return agentId;
    }

    public WxCpService getWxCpService(int index){
        return WxCpConfiguration.getCpService(getAgentId(index));
    }
    /**
     * 获取客户联系我的二维码参数
     * @return
     * @throws WxErrorException
     */
    public WxCpContactWayResult getContactMe(WxCpContactWayInfo.ContactWay contactWay) throws WxErrorException {
        WxCpContactWayInfo wxCpContactWayInfo=new WxCpContactWayInfo();

        wxCpContactWayInfo.setContactWay(contactWay);
        WxCpContactWayResult result=getWxCpService(0).getExternalContactService().addContactWay(wxCpContactWayInfo);
        System.out.println("联系我结果:"+JSONUtil.toJsonStr(result));
        if (result.success()){
            return result;
        }
        return null;
    }
    /**
     * 获取有客户联系权限的成员列表
     * @return
     * @throws WxErrorException
     */
    public  List<String> listFollowUsers() throws WxErrorException {
        List<String> userIds=getWxCpService(0).getExternalContactService().listFollowers();
        System.out.println("有跟踪权限结果:"+JSONUtil.toJsonStr(userIds));
        return userIds;
    }
//    /**
//     * 检查是否用户是否有客户联系功能(内部应用没有这个接口)
//     * @param userIds
//     * @return
//     * @throws WxErrorException
//     */
//    public  List<String> checkFollowUserId(List<String> userIds) throws WxErrorException {
//        getWxCpService(0).getExternalContactService().listFollowers();
//        WxCpService wxCpService=getWxCpService(0);
//        JSONObject jsonObject=new JSONObject();
//        jsonObject.set("user_id",new JSONArray(userIds).toString());
//        String content=wxCpService.get(wxCpService.getWxCpConfigStorage().getApiUrl(CHECK_USER_FOLLOW_USER_URL),jsonObject);
//        JSONObject txlTokenJson=new JSONObject(content);
//        if (txlTokenJson.getInt("errcode")==0){
//            JSONArray authorizedUserIds=txlTokenJson.getJSONObject("authorized").getJSONArray("userid");
//            System.out.println("成员检查结果:"+JSONUtil.toJsonStr(txlTokenJson));
//            return authorizedUserIds.toList(String.class);
//        }else {
//            throw new BaseException("获取客户失败");
//        }
//    }

    /**
     * 获取成员的客户列表
     * 没有成员的时候，错误代码：84061, 错误信息：不存在外部联系人的关系，微信原始报文：{"errcode":84061,"errmsg"}。但是没有异常，返回new ArrayList<String>()
     * @param userId
     * @return
     * @throws WxErrorException
     */
    public List<String> getExternalUserId(String userId) throws WxErrorException {
        List<String> list=getWxCpService(0).getExternalContactService().listExternalContacts(userId);
        System.out.println("成员"+userId+"的客户结果"+ JSONUtil.toJsonStr(list));
        return list;
    }

    /**
     * 获取客户详情
     * @param userId
     * @param cursor
     * @return
     * @throws WxErrorException
     */
    public WxCpExternalContactInfo getExternalUserDetail(String userId,String cursor) throws WxErrorException {
        return getWxCpService(0).getExternalContactService().getContactDetail(userId,cursor);
    }
}